package cn.com.cookie;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "userCookie", value = "/userCookie")
public class userCookie extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建Cookie对象，参数是键和值
        Cookie userCookie = new Cookie("username", "张三");

// 设置Cookie的有效期（秒），这里设置为1天
        userCookie.setMaxAge(24 * 60 * 60);

// 设置Cookie的路径，"/"表示整个网站都可以访问
        userCookie.setPath("/");

// 将Cookie添加到响应中，发送给浏览器
        response.addCookie(userCookie);

        // 从请求中获取所有Cookie
        Cookie[] cookies = request.getCookies();

// 判断是否有Cookie
        if (cookies != null) {
            // 遍历所有Cookie
            for (Cookie cookie : cookies) {
                // 获取Cookie的名称
                String name = cookie.getName();
                String value = cookie.getValue();
                System.out.println(name+"=" + value);
                // 判断是否是我们需要的Cookie
//                if ("username".equals(name)) {
//                    // 获取Cookie的值
//                    String value = cookie.getValue();
//                    System.out.println("用户名：" + value);
//                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}